<?php
/*
 * utils.php
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

define ( "DATE_KIND_UNIVERSAL",		"1" );
define ( "DATE_KIND_ITALIAN",		"2" );
define ( "DATE_KIND_AMERICAN",		"3" );

define ( "SAFE_MODE_UNSET",		0 );	// No safe check performed
define ( "SAFE_MODE_NUMBER",		1 );	// The data MUST be a number
define ( "SAFE_MODE_STRING",		2 );	// Just a string
define ( "SAFE_MODE_DB_STRING",		3 );	// The data must be a string that can be saved inside a DB
define ( "SAFE_MODE_MONEY",		4 );	// The data ha sthe format "1.000.212,15"
define ( "SAFE_MODE_BOOL",		5 );	// If data exists, it is TRUE
define ( "SAFE_MODE_DATE",		6 );	// The data is a date in YYYY-MM-DD format
define ( "SAFE_MODE_DB_BOOL",		7 );	// If data exists, it is 1
define ( "SAFE_MODE_HTML",		8 );	// The data is an HTML source
define ( "SAFE_MODE_DB_HTML",		9 );	// The data is an HTML source that can be saved inside a DB

// Shows an error on the screen
function util_display_error ( $err_msg, $info = "" )
{
	global $__wbench;

	// return;
	// if ( $__wbench->_show_errors == false ) return;

	$str  = "<div align=\"center\"><br><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td bgcolor=\"#000000\">\n";
	$str .= "<table border=\"0\" cellpadding=\"5\" cellspacing=\"1\">\n";
	$str .= "<tr><td bgcolor=\"#ff0000\" align=\"center\"><font size=\"+2\">ERROR</font></td></tr>\n";
	$str .= "<tr><td bgcolor=\"#ffffff\" align=\"justify\"><font face=\"Arial\">$err_msg</td></tr>\n";
	if ( $info != "" ) $str .= "<tr><td bgcolor=\"#ffffff\" align=\"justify\"><font face=\"Arial\">$info</td></tr>\n";
	$str .= "</table></td></tr></table></div>\n";

	print ( $str );
}


// This function scans a directory and returns all
// dir names it founds except for those starting with a '.'
// or the CVS dir.
// Mainly, this is useful to scan "themes" and "plugins" dir
// since every theme/plugin has its own directory
function & util_get_dirs ( $dir_name )
{
	$arr = null;

	if ( ( $dir = @opendir( $dir_name ) ) ) 
	{
		$arr = array();
		$count = 0;

		while ( ( $file = readdir ( $dir ) ) ) 
		{
			if ( $file[0] == '.' ) continue;
			if ( $file == 'CVS' ) continue;
			if ( $file == 'trash' ) continue;

			if ( is_dir ( "$dir_name/$file" ) || is_link ( "$dir_name/$file" ) ) $arr [ $count++ ] = $file;
  		}  
  		closedir($dir);

		return $arr;
	}

	return $arr;
}

function util_mklink ( $plugin_name, $mode, $txt, $add_fields = "", $target = false, $over = false )
{
	$url = util_mkhref ( $plugin_name, $mode, $add_fields );

	$str = "<a href=\"$url\"";

	if ( $target ) $str .= " target=\"$target\"";
	if ( $over ) $str .= " onMouseOver=\"laybox_show ( '" . util_valid_js ( $over ) . "')\" onMouseOut=\"laybox_hide ()\"";
	$str .= ">$txt</a>";

	return ( $str );
}

function util_valid_js ( $str )
{
	$str = str_replace ( array ( "\n", "\r" ), "", $str );

	$str = strip_tags ( $str, "<b> <font> <i> <u> <img> <table> <tr> <td> <tbody> <br> <div> <span>" );

	$str = eregi_replace ( "(onmouse.*|alt|width|border|height|align|title)=.[^'\"]*['\"]", "", $str );
	$str = eregi_replace ( '"', '&quot;', $str );

	return ( util_addslashes ( $str ) );
}

function util_string_valid ( $str, $chars )
{
	for ( $t = 0; $t < strlen ( $str ); $t++ )
		if ( stristr ( $chars, $str [ $t ] ) == false ) return ( false );

	return ( true );
}

function util_string_valid_ranges ( $str, $alpha = true, $num = true, $addit = false )
{
	$chars = "";

	if ( $alpha ) $chars .= "abcdefghijklmnopqrstuvwxyz";
	if ( $num   ) $chars .= "0123456789";
	if ( $addit ) $chars .= $addit;

	return ( util_string_valid ( $str, $chars ) );
}


function & util_scan_dir ( $dir_name, $dirs = true, $files = false, $links = false )
{
	$arr = false;

	if ( $dir = @opendir( $dir_name ) ) 
	{
		$arr = array();

		while ( $file = readdir ( $dir ) ) 
		{
			if ( $file[0] == '.' ) continue;
			if ( $file == 'CVS' )  continue;
			if ( $file == 'trash') continue;

			if ( ( $dirs ) && ( @ is_dir ( "$dir_name/$file" ) ) ) $arr [] = $file;
			if ( ( $files ) && ( @ is_file ( "$dir_name/$file" ) ) ) $arr [] = $file;
			if ( ( $links ) && ( @ is_link ( "$dir_name/$file" ) ) ) $arr [] = $file;
  		}  
  		closedir($dir);

		sort ( $arr );

		return $arr;
	}

	return $arr;
}

function util_read_file ( $fname )
{
	$fd = @ fopen ( $fname, "r");
	if ( $fd == false ) return ( false );

	$contents = fread ($fd, filesize ( $fname ) );
	fclose ($fd);

	return $contents;
}

function util_timestamp_to_str ( $ts )
{
	$year = substr ( $ts, 0, 4 );
	$mm   = substr ( $ts, 5, 2 );
	$dd   = substr ( $ts, 8, 2 );
	$hh   = substr ( $ts, 11, 2 );
	$m    = substr ( $ts, 14, 2 );
	$ss   = substr ( $ts, 17, 2 );
	
	return ( "$year-$mm-$dd $hh:$m.$ss" );
}

function util_addslashes ( $str )
{
	if ( ( strstr ( $str, "\\'" ) === false ) && ( strstr ( $str, "\\\"" ) === false ) )
		return addslashes ( $str );

	return ( $str );
}

function util_relocation ( $new_url )
{
	header ( "Location: $new_url" );
}

function util_split_date ( $date, $kind = DATE_KIND_UNIVERSAL )
{
	$year = "";
	$month = "";
	$day = "";

	switch ( $kind )
	{
		case DATE_KIND_UNIVERSAL:
			$year = substr ( $date, 0, 4 );
			$month = substr ( $date, 5, 2 );
			$day   = substr ( $date, 8, 2 );
			break;

		case DATE_KIND_ITALIAN:
			$day 	= substr ( $date, 0, 2 );
			$month 	= substr ( $date, 3, 2 );
			$year   = substr ( $date, 6, 4 );
			break;

		case DATE_KIND_AMERICAN:
			$day 	= substr ( $date, 3, 2 );
			$month 	= substr ( $date, 0, 2 );
			$year   = substr ( $date, 6, 4 );
			break;
	}

	// o_out ( "<h1>DAY: $day - MONTH: $month - YEAR: $year</h1>" );

	return ( array ( "day" => $day, "month" => $month, "year" => $year ) );
}

function util_email_message ( $dest_email, $subject, $msg, & $wb, $bcc = false )
{
	$from_name  = $wb->cfg [ "EMAIL_FROM_NAME" ];
	$from_email = $wb->cfg [ "EMAIL_FROM_EMAIL" ];

	$p = new pmail ( $subject, $from_name, $from_email, $dest_email, $bcc );

	$p->text ( $msg );
	$p->send ();
}

/*
	Returns the value (if any) of a form field
	The order of search can be specified by using the "order" variable

	P	- Post Forms
	G	- Get Forms
	R	- Request Vars
	X	- Server Vars	
	C	- Cookie Variables

	if you set the $clear variable to TRUE, the value will be removed from the array
	and the result will not be cached in the wb->form_results array.

	if you omit any of the letters above, the search will not be accomplished there.
	NOTE: data is retrieved and then stripped with stripslashes
*/
function & util_ff ( $name, $order = "PGRXC", $safe_mode = SAFE_MODE_UNSET, $default = 0xdeadbeef )
{
	global $wb, $__html_fields;

	if ( ( $wb ) && ( isset ( $wb->form_results [ $name ] ) ) ) return ( $wb->form_results [ $name ] );

	$len = strlen ( $order );

	$v = 0xdeadbeef;

	for ( $t = 0; $t < $len; $t ++ )
	{
		$o = $order{$t};

		switch ( $o )
		{
			case "P":
				if ( isset ( $_POST [ $name ] ) ) $v = $_POST [ $name ];
				break;

			case "G":
				if ( isset ( $_GET [ $name ] ) ) $v = $_GET [ $name ];
				break;

			case "R":
				if ( isset ( $_REQUEST [ $name ] ) ) $v = $_REQUEST [ $name ];
				break;

			case "C":
				if ( isset ( $_COOKIE [ $name ] ) ) $v = $_COOKIE [ $name ];
				break;

			case "X":
				if ( isset ( $_SERVER [ $name ] ) ) $v = $_SERVER [ $name ];
				break;
		}

		if ( $v != 0xdeadbeef ) 	break;
	}

	if ( $v == '' ) $v = 0xdeadbeef;

	if ( $v == 0xdeadbeef )  
	{
		if ( $default != 0xdeadbeef ) return $default;

		$v = false;

		if ( $safe_mode == SAFE_MODE_DB_BOOL ) $v = "0";
		return $v;
	}

	$v = trim ( $v );

	switch ( $safe_mode )
	{
		case SAFE_MODE_NUMBER:
			if ( is_numeric ( $v ) == false ) { $v = false; return $v; };
			$v += 0;
			break;

		case SAFE_MODE_DB_STRING:
			$v = util_addslashes ( $v );
			break;

		case SAFE_MODE_UNSET:
			break;

		case SAFE_MODE_MONEY:
			$v = explode ( ",", str_replace ( ".", "", $v ) );
			$v = sprintf ( "%d%02.2d", $v [ 0 ], $v [ 1 ] );
			break;

		case SAFE_MODE_BOOL:
			if ( $v == 'false' ) $v = 0;
			if ( $v ) $v = true;
			else	  $v = false;
			break;

		case SAFE_MODE_DB_BOOL:
			if ( $v ) $v = "1";
			else	  $v = "0";
			break;

		case SAFE_MODE_DATE:
			preg_match ( '/([0-9]{4}).([0-9]{1,2}).([0-9]{1,2})/', $v, $arr );
			$v = sprintf ( "%04.4d-%02.2d-%02.2d", $arr [ 1 ], $arr [ 2 ], $arr [ 3 ] );
			if ( $v == '0000-00-00' ) $v = false;
			break;

		case SAFE_MODE_HTML:
			$v = util_html_text ( $v );
			break;

		case SAFE_MODE_DB_HTML:
			$v = str_replace ( "'", "\\'", util_html_text ( $v ) );
			break;

		case SAFE_MODE_STRING:
		default:
			if ( is_string ( $v ) ) $v = stripslashes ( $v );
	}

	return $v;
}

function util_sys_err ( $title, $descr, $get_str = false )
{
	$s =  "<div class=\"sys_err\"><div class=\"title\">$title</div><div class=\"descr\">$descr</div></div>";

	if ( ! $get_str ) 
		print $s;
	else 
		return $s;
}

function util_safe_url ( $url )
{
	return str_replace ( " ", "%20", $url );
}

function util_js_str ( $str )
{
	return str_replace ( "\n", "<br />", str_replace ( "\r", "", $str ) );
}

/*
	Restituisce il tempo in "secondi.millisec" 
	a partire dall'epoca.
*/
function util_get_time ()
{
	list ( $usec, $sec ) = explode ( " ", microtime () );
	
	$usec = explode ( ".", "$usec" );
	$usec = $usec [ 1 ];

	return sprintf ( "%d.%07.07d", $sec, $usec );
}

function & util_html_text ( $txt, $valid_tags = '<span><br><table><tr><td><th><tbody><div><a><img>' )
{
	// Prima di tutto, tolgo i tags non validi
	$txt = strip_tags ( stripslashes ( $txt ), $valid_tags );

	$ent = get_html_translation_table ( HTML_ENTITIES );

	error_log ( "TESTO: $txt" );

	unset ( $ent [ '<' ] );
	unset ( $ent [ '>' ] );
	unset ( $ent [ '"' ] );
	unset ( $ent [ "'" ] );
	unset ( $ent [ "&" ] );

	// Poi converto le entities in HTML
	$txt = str_replace ( "\r", "", strtr ( $txt, $ent ) );

	// Adesso, con una bella regexp, converto i "<" e ">"
	$txt = ereg_replace ( "<([^/a-zA-Z]+)", '&lt;\1', $txt );
	$txt = ereg_replace ( "([^a-z]+)>", '\1&gt;', $txt );

	error_log ( "TESTO2: $txt" );

	return $txt;
}

function format_dict ( $format, & $args )
{
	$re = '/%\(([^)]*)\)([0+#-]*)([0-9]*)(\.{0,1})([0-9]*)([ds])/';
	$res = '';

	while ( ( preg_match ( $re, $format, $matches, PREG_OFFSET_CAPTURE ) ) )
	{

		$p1 = array_shift ( $matches );
		$f1 = array_shift ( $matches );

		$left  = substr ( $format, 0, $p1 [ 1 ] ); 
		$right = substr ( $format, $p1 [ 1 ] + strlen ( $p1 [ 0 ] ) );

		$fmt = "%";
		foreach ( $matches as $m ) $fmt .= $m [ 0 ];
		
		$repl  = @ sprintf ( $fmt, $args [ $f1 [ 0 ] ] );
		$format = $left . $repl . $right;
	}

	return $format;
}


?>
